var Endpoints = new Object();
var idNumber = 0;
var inputText;
var saveObject=new Object();
var dataSource=new Object();
var repeatcheck=new Array();
var color1 = "red";
var instance = jsPlumb.importDefaults({
	DragOptions : {cursor : 'pointer'	},
	PaintStyle : { strokeStyle:color1 },
	EndpointStyle : { width:20, height:20, strokeStyle:color1 },
	Endpoint : "Rectangle",
	ConnectionOverlays : [[ "Arrow", { width:20, length:30, location:0.5,  }],],
    });
var calEndpointIn1 = {
	endpoint : ["Rectangle",{width:20, length:20 } ],
	connectorOverlays:[  [ "Arrow", { width:20, length:30, location:0.5,  } ],],
	paintStyle : {fillStyle : color1,opacity : 0.5	},
	anchor : [ 0, 0 ],
	isSource : false, 
	scope : "green dot",
	connectorStyle : {strokeStyle : color1,		lineWidth : 3	},
	connector : [ "Bezier", {	curviness : 63	} ],
	maxConnections : 1,
	isTarget : true, 
    onMaxConnections : function(info) {	alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);	}
    };
var calEndpointIn2 = {
	endpoint : ["Rectangle",{width:20, length:20 } ],
	connectorOverlays:[    [ "Arrow", { width:20, length:30, location:0.5,  } ],],
	paintStyle : {		fillStyle : color1,opacity : 0.5	},
	anchor : [ 1, 0 ],
	isSource : false,
	scope : "green dot",
	connectorStyle : {strokeStyle : color1,lineWidth : 3	},
	connector : [ "Bezier", {	curviness : 63	} ],
	maxConnections : 1,
	isTarget : true,
    onMaxConnections : function(info) {alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);}
    };
var calEndpointOut1 = {
	endpoint : ["Rectangle",{width:20, length:20 } ],
	connectorOverlays:[  [ "Arrow", { width:20, length:30, location:0.5,  } ],  ],
	paintStyle : {fillStyle : color1,	opacity : 0.5	},
	anchor : [ 0.5, 1 ],
	isSource : true,
	scope : "green dot",
	connectorStyle : {	strokeStyle : color1,lineWidth : 3	},
	connector : [ "Bezier", {	curviness : 63	} ],
	maxConnections : 1,
	isTarget : false,
    onMaxConnections : function(info) {	alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);}
    };
var dataEndpointOut1 = {endpoint : ["Rectangle",{width:20, length:20 } ],
	connectorOverlays:[    [ "Arrow", { width:20, length:30, location:0.5,  } ],   ],
	paintStyle : {		fillStyle : color1,		opacity : 0.5	},
	anchor : [ 0.5, 1 ],
	isSource : true, 
	scope : "green dot",
	connectorStyle : {		strokeStyle : color1,		lineWidth : 3	},
	connector : [ "Bezier", {		curviness : 63	} ],
	maxConnections : 1,
	isTarget : false, 
    onMaxConnections : function(info) {		alert("Cannot drop connection " + info.connection.id + " : maxConnections has been reached on Endpoint " + info.endpoint.id);}
    };
var commonleft={
		anchors:["BottomCenter", "TopLeft" ],
        endpoints:["Rectangle", "Rectangle" ],
        ConnectionOverlays : [  [ "Arrow", { width:20, length:30, location:0.5,  } ],      	],
     }
var commonright={
	   anchors:["BottomCenter", "TopRight"],
       endpoints:["Rectangle", "Rectangle" ],
       ConnectionOverlays : [  	 [ "Arrow", { width:20, length:30, location:0.5,  } ],],
     }


function adddatasource(){
	$(".btn.btn-default.data").click(
	function(){
		idNumber = idNumber + 1;
		inputText = $(this).text();
		var divName = "flowchartWindow" + idNumber;
		$("#scope").append("<div class=\"window\" id=\"" + divName + "\" sourceType=\"description\"><h1>" + inputText + "</h1></div>");
		jsPlumb.draggable(divName, {containment : "parent"});
		Endpoints[divName] = new Array();		
		test = jsPlumb.addEndpoint(divName, dataEndpointOut1);
		Endpoints[divName].push(test);		
		deleteFunction();
		})}
function getRelationData() {
    $.ajax({
	url : "../rest/relation/getRelationContent",
	data : {
	    "path" : $("#pathValue").val()
	},
	dataType : "JSON",
	method : "POST",
	success : function(data) {
	    addColumn(data);
	    initialCanvas(data) ;
	    $("#messageArea").html("add relation success......");
	},
	error : function(data) {
	    $("#messageArea").html("connect error, status:" + data.status + " ,message:" + data.statusText);
	}
	
    });
    }

function initialCanvas(data) {
}

function addColumn(data)
{ 
	dataSource=data;
    var keys=data["csv-key"].split('|');
    $.each(keys,function(k,v){
	$("#columnButtonGroup").append("<button type='button' class='btn btn-default data' >"+v+"</button>");
    }); 
    adddatasource();
 }

function addcalCalculation(){
	$(".btn.btn-default.cal").click(
	function(){
		idNumber = idNumber + 1;
		inputText = $(this).text();
		var divName = "flowchartWindow" + idNumber;
		$("#scope").append("<div class=\"window\" id=\"" + divName + "\" sourceType=\"calculation\"><h1>" + inputText + "</h1></div>");
		jsPlumb.draggable(divName, {containment : "parent"});
		Endpoints[divName] = new Array();
		test = jsPlumb.addEndpoint(divName, calEndpointIn1);
		Endpoints[divName].push(test);
		test = jsPlumb.addEndpoint(divName, calEndpointIn2);
		Endpoints[divName].push(test);
		test = jsPlumb.addEndpoint(divName, calEndpointOut1);
		Endpoints[divName].push(test);
		deleteFunction();
	})}

function deleteFunction(){
	$(".window").dblclick(function() {
		var name = $(this).attr("id");
		var i = Endpoints[name].length;
		jsPlumb.detachAllConnections(this);
		$.each(Endpoints[name],function(i){
			jsPlumb.deleteEndpoint(Endpoints[name][i]);	
		}	
		)
		$(this).remove();
	})}

function saveRelation(){
	$("#save-btn").click(
	function(){
 
		var saveObject=new Object();
		$.each(jsPlumb.getAllConnections(),function(k,v){
			saveObject[v.sourceId]=new Object();
			saveObject[v.sourceId]["value"]=$("#"+v.sourceId).text();
			saveObject[v.sourceId]["top"]=$("#"+v.sourceId).css("top");
			saveObject[v.sourceId]["left"]=$("#"+v.sourceId).css("left");
			saveObject[v.sourceId]["type"]=$("#"+v.sourceId).attr("sourceType");
			if(v.endpoints[1].anchor.x<1){
				saveObject[v.sourceId]["order"]="leftside";
			}else{
				saveObject[v.sourceId]["order"]="rightside";
			}
			saveObject[v.sourceId]["target"]=new Object();
			saveObject[v.sourceId]["target"]["ID"]=v.targetId;
			saveObject[v.sourceId]["target"]["value"]=$("#"+v.targetId).text();
			saveObject[v.sourceId]["target"]["top"]=$("#"+v.targetId).css("top");
			saveObject[v.sourceId]["target"]["left"]=$("#"+v.targetId).css("left");
			saveObject[v.sourceId]["target"]["type"]=$("#"+v.targetId).attr("sourceType");	
		});
		dataSource["connections"]=saveObject;
        var check= new Array();
        var line = new Object();
        var temp=new Object();
		$.each(dataSource["connections"],function(k,v){
			if(check.indexOf(k)==-1){
         	   if(check.indexOf(v.target.ID)==-1){
         		   line[v.target.ID]=v.value+" "+v.target.value;
         		  temp=line[v.target.ID];
         	   }
         	   else{
         		   line[v.target.ID]=line[v.target.ID]+" "+v.value;
         		  temp=line[v.target.ID];
         	   }
            }
            else{
                if(check.indexOf(v.target.ID)==-1){
             	   line[v.target.ID]="("+line[k]+")"+" "+v.target.value;
             	  temp=line[v.target.ID];
         	   }
         	   else{
         		   line[v.target.ID]=line[v.target.ID]+" "+"("+line[k]+")";
         		  temp=line[v.target.ID];
         	   }
            }
 		   check.push(k);
 		   check.push(v.target.ID);		
		} ) 
		dataSource["translation"]=line;
		debugger
//	    $.ajax({
//	    	url : "../rest/relation/editRelationFilter",
//	    	data : {"data":dataSource},
//	    	dataType : "JSON",
//	    	method : "POST",
//	    	success : function(data) {
//	    	    $("#messageArea").html("save success......");
//	    	},
//	    	error : function(data) {
//	    	    $("#messageArea").html("connect error, status:" + data.status + " ,message:" + data.statusText);
//	    	}
//	        });
	})}

function reloadReload(){
	$("#reload-btn").click(
	function(){
		repeatcheck=new Array();
		$.each(dataSource["connections"],function(k,v){
			var leftrightcheck="left";
			if(repeatcheck.indexOf(k)==-1)
			{ 
			           if(v.type=="description")
			           {
							$("#scope").append("<div class=\"window\" id=\"" + k + "\"  sourceType=\"description\"><h1>" + v.value + "</h1></div>");
							$("#"+k).css({"left":v.left,"top":v.top});
							jsPlumb.draggable(k, {containment : "parent"});
							Endpoints[k] = new Array();		
							test = jsPlumb.addEndpoint(k, dataEndpointOut1);
							Endpoints[k].push(test);		
							deleteFunction();
							repeatcheck.push(k);
						}
			}
			if(repeatcheck.indexOf(v.target.ID)==-1)
			{
			        $("#scope").append("<div class=\"window\" id=\"" + v.target.ID + "\" sourceType=\"calculation\"><h1>" + v.target.value + "</h1></div>");
					$("#"+v.target.ID).css({"left":v.target.left,"top":v.target.top});
					jsPlumb.draggable(v.target.ID, {containment : "parent"});
					Endpoints[v.target.ID] = new Array();
					test = jsPlumb.addEndpoint(v.target.ID, calEndpointIn1);
					Endpoints[v.target.ID].push(test);
					test = jsPlumb.addEndpoint(v.target.ID, calEndpointIn2);
					Endpoints[v.target.ID].push(test);
					test = jsPlumb.addEndpoint(v.target.ID, calEndpointOut1);
					Endpoints[v.target.ID].push(test);
					deleteFunction();
					repeatcheck.push(v.target.ID);
			}
						if(v.order=="leftside")
						{
							jsPlumb.connect({source:k,target:v.target.ID},commonleft);
						}
						else if(v.order=="rightside")
						{
							jsPlumb.connect({source:k,target:v.target.ID},commonright);
						}
		})}	)}


function clearRelation(){
	$("#clear-btn").click(
	function(){
		var confirmtext=confirm("Clear all relations without save?");
		if (confirmtext==true)
			{
			document.getElementById("scope").innerHTML="";
			alert("All relations cleared");
			}
	})} 
function inputValues(){
	$(".btn.btn-default.input").click(
	function (){
		idNumber = idNumber + 1;
		inputText = $("#inputtext").val();
		var divName = "flowchartWindow" + idNumber;
		$("#scope").append("<div class=\"window\" id=\"" + divName + "\" sourceType=\"description\"><h1>" + inputText + "</h1></div>");
		jsPlumb.draggable(divName, {containment : "parent"});
		Endpoints[divName] = new Array();		
		test = jsPlumb.addEndpoint(divName, dataEndpointOut1);
		Endpoints[divName].push(test);		
		deleteFunction();
	}		
	)
}

var sourceArea= new Array();
var targetArea= new Array();
var testObject= new Object();

function testFunction(){
   $("#test-btn").click(
	function(){
		debugger
		testObject=saveObject;
		$.each(testObject,function(k,v){
			sourceArea.push(k);
			targetArea.push(v.target.ID)
		})
		var i=1;
		$.each(targetArea,function(k,v){
			if(sourceArea.indexOf(v)==-1){
				//标记最后一组ID
				alert(i),
				i++;
				delete sourceArea[k];
				delete targetArea[k];

//				sourceID = sourceArea[k];
//				targetID = targetArea[k];
//				idNumber = idNumber + 1;
//				inputText = saveObject[targetID].value;
//				var divName = "flowchartWindow" + idNumber;
//				$("#scope").append("<div class=\"window\" id=\"" + divName + "\" sourceType=\"calculation\"><h1>" + inputText + "</h1></div>");
//				jsPlumb.draggable(divName, {containment : "parent"});
//				Endpoints[divName] = new Array();
//				test = jsPlumb.addEndpoint(divName, calEndpointIn1);
//				Endpoints[divName].push(test);
//				test = jsPlumb.addEndpoint(divName, calEndpointIn2);
//				Endpoints[divName].push(test);
//				test = jsPlumb.addEndpoint(divName, calEndpointOut1);
//				Endpoints[divName].push(test);
//				idNumber = idNumber + 1;
//				inputText = saveObject[sourceID].value;
//				var divName = "flowchartWindow" + idNumber;
//				$("#scope").append("<div class=\"window\" id=\"" + divName + "\" sourceType=\"description\"><h1>" + inputText + "</h1></div>");
//				jsPlumb.draggable(divName, {containment : "parent"});
//				Endpoints[divName] = new Array();		
//				test = jsPlumb.addEndpoint(divName, dataEndpointOut1);
//				Endpoints[divName].push(test);		
//				deleteFunction();
			}
		})
	}	   
   )	
}





//main function
$(function() {
     getRelationData();
     initialCanvas();
     addcalCalculation(); 	
     deleteFunction();
     saveRelation();
     reloadReload();
     clearRelation();
     inputValues();
     testFunction();
     
})